package com.yx.cloud.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.graphics.Bitmap;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.iot.base.service.req.RemoveSharedUserParam;
import com.iot.common.utils.LogUtils;
import com.iot.sweeper.AppContext;
import com.yx.cloud.R;
import com.yx.cloud.adapter.SharEquipmentAdapter;
import com.yx.cloud.base.BaseActivity;
import com.yx.cloud.databinding.SharequipmentActivityBinding;
import com.yx.cloud.product.ProductConfigConstants;
import com.yx.cloud.utils.Intent_utils;
import com.yx.cloud.utils.RomUtils;
import com.yx.cloud.utils.ToastUtil;
import com.iot.base.bean.account.Account;
import com.iot.common.utils.Event;

import java.util.ArrayList;
import java.util.List;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * 创建时间 : 2018/12/26.
 * 创建人 :
 * 功能描述 :设备共享界面
 */
public class SharEquipmentActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "SharEquipmentActivity";
    private Dialog dialog;
    private Account account;
    private List<Account> mList;
    private SharEquipmentAdapter adapter;
    private SharequipmentActivityBinding binding;

    @Override
    public void onCreate() {
        binding = SharequipmentActivityBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        initData();
    }


    private void initData() {
        mList = new ArrayList<>();
        adapter = new SharEquipmentAdapter(SharEquipmentActivity.this, mList);
        try {
            account = AppContext.get().getAccount();
            if (account != null) {
                {
                    if (account.getHeadPic() != null) {
                        binding.ivShareheadPicMian.setImageBitmap(account.getHeadPic());
                    } else {
                        AppContext.getAccountService().getUserProfile(account.getHeadPicUrl());
                    }
                }
            }
            binding.tvIphoneNumMian.setText(account.getAccount());
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        adapter.notifyDataSetChanged();

        // 根据pid判断机器型号，进行分类显示图片
        binding.firmwareUpdateIcon.setImageResource(AppContext.getConfig().optInt(ProductConfigConstants.robot_transparent_icon));
        binding.sharListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ImageView sharDetele = view.findViewById(R.id.iv_sharDelete);
                sharDetele.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (RomUtils.isFastClick()) {
                            return;
                        }
//                        String userId = mList.get(position).getId();
                        String account = mList.get(position).getAccount();
                        String result = getResources().getString(R.string.MO_RobotShare_Delete_Tip).replace("{X}", account);
                        deleteSharDialog(result, account);

                    }
                });
            }
        });

        binding.ivSharEquipmentReturn.setOnClickListener(this);
        binding.ivAddShare.setOnClickListener(this);

    }

    @Override
    protected void onStart() {
        super.onStart();
        queryShare();
    }


    @Override
    public void onClick(View v) {
        if (RomUtils.isFastClick()) {
            return;
        }
        int id = v.getId();
        if (id == R.id.iv_sharEquipmentReturn) {
            Intent_utils.backIntent(this);
        } else if (id == R.id.iv_addShare) {
            Intent_utils.enterIntentMenu(this, AccountShareActivity.class);
        }
    }

    //查询分享信息 接口调用
    private void queryShare() {
        AppContext.getProductService().getSharedUser();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Event event) {
        switch (event.getType()) {
            case Event.MESSAGE_TYPE_QUERY_SHARE_USER:
                if (event.isResult()) {
                    mList.clear();
                    List<Account> accountList = (List<Account>) event.getContent();
                    mList.addAll(accountList);
//                    for (int i = 0; i <accountList.size() ; i++) {
//                        asyncloadImage(accountList.get(i).getHeadPicUrl());
//                    }
//                    SharEquimentBean bean;
//                    for (int i = 0; i < accountList.size(); i++) {
//                        bean = new SharEquimentBean();
//                        bean.setAccount(accountList.get(i).getAccount());
//                        bean.setUserId(accountList.get(i).getUserId());
////                        bean.setBitmap(bitmaps.get(i));
//                        mList.add(bean);
//                    }
                    LogUtils.i("查询分享信息成功 : mList--> :" + mList.size());
                    binding.sharListView.setAdapter(adapter);
                } else {
                    LogUtils.i("查询分享信息失败 : --> :");
                }

                break;
            case Event.MESSAGE_TYPE_DOWNLOAD_HEADPICTRUE:
                //自动更新头像
                if (event.isResult()) {
                    Bitmap bitmap = (Bitmap) event.getContent();
                    binding.ivShareheadPicMian.setImageBitmap(bitmap);
                } else {
                    //ToastUtil.show(SharEquipmentActivity.this, event.getContent().toString(), Toast.LENGTH_SHORT);
                }
                break;
            case Event.MESSAGE_TYPE_REMOVE_SHARE_USER:
                //删除分享
                if (event.isResult()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            queryShare();
                            adapter.notifyDataSetChanged();
                            ToastUtil.show(SharEquipmentActivity.this, getString(R.string.U_T_Delete_Ok), Toast.LENGTH_SHORT);
                        }
                    });
                } else {
                    ToastUtil.show(SharEquipmentActivity.this, event.getContent() + "", Toast.LENGTH_SHORT);
                }
                break;
        }
    }

    private void deleteSharDialog(String dialogTitle, String account) {
        Dialog dialog = new Dialog(SharEquipmentActivity.this);
        dialog.setContentView(R.layout.content_centered_dialog);
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        dialog.setCanceledOnTouchOutside(false);
        TextView mBtnOutLoginConfirm = dialog.findViewById(R.id.btn_centered_Confirm);
        TextView mBtnOutLoginCancel = dialog.findViewById(R.id.btn_centered_Cancel);
        TextView mTvDialogTitle = dialog.findViewById(R.id.tv_centered_dialogTitle);
        TextView mTvDialogContent = dialog.findViewById(R.id.tv_centered_dialogContent);
        mTvDialogTitle.setText(dialogTitle);
        mTvDialogContent.setVisibility(View.GONE);
        mBtnOutLoginConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                RemoveSharedUserParam param = new RemoveSharedUserParam();
                param.setUserId(account);
                AppContext.getProductService().removeSharedUser(param);
                dialog.dismiss();
            }
        });
        mBtnOutLoginCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();

            }
        });
        dialog.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
}
